
export default async function importComponent(scope, module) {
    const container = await installContainer(scope);
    const Module = await loadComponent(container, module);
    // const Module = await loadComponent(window[scope], module);
    return Module;
}

function installContainer(scope) {
    return new Promise(resolve => {
        const remoteUrl = `http://localhost:3001/${scope}.js`
        const script = document.createElement('script')
        script.src = remoteUrl
        script.onload = () => {
            const proxy = {
                get: (request) => window[scope].get(request),
                init: (arg) => {
                    try {
                        return window[scope].init(arg)
                    } catch (e) {
                        console.log('remote container already initialized')
                    }
                }
            }
            resolve(proxy)
        }
        document.head.appendChild(script);
    })
}

async function loadComponent(container, module) {
    await __webpack_init_sharing__('default');
    await container.init(__webpack_share_scopes__.default);
    const factory = await container.get(module);
    const Module = factory();
    return Module;
}